package com.mobiusws.general;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AccessFilter implements Filter {
	
	private static String[] validStrings={"/login.jsp","/logIn.action","/css/","/js/",".dtd",".kmz"};

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
	
	private boolean containsValidStr(String uriStr) {
		boolean containsValid=false;
		for(String str:validStrings) {
			if(uriStr.contains(str)) {
				containsValid=true;
				break;
			}
		}
		return containsValid;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String uriStr = httpRequest.getRequestURI();
		boolean isValid = false;
		//System.out.println(uriStr);
		if (containsValidStr(uriStr)) {
			isValid = true;
		} else {
			HttpSession session = httpRequest.getSession();
			String username = (String) session.getAttribute("username");
			if (username == null || "".equals(username)) {
				isValid=false;
			} else {
				isValid=true;
			}
		}
		
		if(isValid) {
			filterChain.doFilter(request, response);
		} else {
			((HttpServletResponse)response).sendRedirect("login.jsp");
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
